package com.wst.system.config;

import com.wst.system.util.RandomNumber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class SecretKeyComponent {

    private Map<String, String> secryptModelMap;

    private String secretDate;

    public String getSecretKey(String sessionId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date= dateFormat.format(new Date());
        if(!this.secretDate.equals(date)){
            this.flushSecryptModelMap();
        }
        return this.secryptModelMap.get(sessionId);
    }

    public String getSessionId() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date= dateFormat.format(new Date());
        if(!this.secretDate.equals(date)){
            this.flushSecryptModelMap();
        }
        Set<String> keySet = secryptModelMap.keySet();
        // 将 key 集合转换为数组
        String[] keysArray = keySet.toArray(new String[0]);
        // 生成一个随机索引
        Random random = new Random();
        int randomIndex = random.nextInt(keysArray.length);
        // 获取随机的 key
        String randomKey = keysArray[randomIndex];
        return randomKey;
    }

    public void flushSecryptModelMap(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        this.secretDate=dateFormat.format(new Date());
        this.secryptModelMap = new ConcurrentHashMap<>();
        for (int i = 0; i < 3000  ; i++) {
            String sessionId=String.valueOf(RandomNumber.generateRandomNumber(8))+String.valueOf(RandomNumber.generateRandomNumber(8));
            boolean isexist=true;
            while(isexist) {
                if(!secryptModelMap.containsKey(sessionId)) {
                    isexist=false;
                }else {
                    sessionId=String.valueOf(RandomNumber.generateRandomNumber(8))+String.valueOf(RandomNumber.generateRandomNumber(8));
                }
            }
            String key=RandomNumber.generateRandomNumberStr(16);
            this.secryptModelMap.put(sessionId, key);
        }
    }

    @Bean
    public void initSecryptModel() {
        this.flushSecryptModelMap();
    }
}
